package com.qf.blog.controller.system;

import com.alibaba.fastjson.JSON;
import com.qf.blog.core.constants.BaseConstants;
import com.qf.blog.core.servlet.BaseServlet;
import com.qf.blog.entity.SystemUserEntity;
import com.qf.blog.service.ISystemUserService;
import com.qf.blog.service.impl.SystemUserServiceImpl;
import org.springframework.context.ApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/SystemUserServlet/*")
public class SystemUserServlet extends BaseServlet {

//    private ISystemUserService systemUserService = new SystemUserServiceImpl();

    private ISystemUserService systemUserService;

    // 在这个方法中从上下文获取IOC容器，从容器中获取Service对象给上面属性赋值
    @Override
    public void myInit() {
        ApplicationContext ctx = (ApplicationContext) this.req.getServletContext().getAttribute("spring");
        systemUserService = ctx.getBean("systemUserService", ISystemUserService.class);
    }

    public void list() throws Exception {
        // 1.查询数据
        List<SystemUserEntity> list = systemUserService.list();

        // 2.把数据放到Map中
        Map<String, Object> map = new HashMap<>();
        map.put("sysUserList", list);

        // 3.跳转到视图
        outView("system/sysUser/sysUserList", map);
    }


    public String add() throws Exception {
        String json = super.req.getReader().readLine();
        SystemUserEntity systemUser = JSON.parseObject(json, SystemUserEntity.class);
        systemUser.setStatus(0);
        boolean save = systemUserService.save(systemUser);
        return outJson(save);
    }

    public void systemUserById() throws Exception {
        String id = this.req.getParameter("id");
        SystemUserEntity systemUser = systemUserService.byId(Integer.parseInt(id));
        Map<String, Object> map = new HashMap<>();
        map.put("systemUser", systemUser);
        outView("/system/sysUser/sysUserUpdate", map);
    }

    public String update() throws Exception {
        String json = super.req.getReader().readLine();
        SystemUserEntity systemUser = JSON.parseObject(json, SystemUserEntity.class);
        boolean save = systemUserService.update(systemUser);
        return outJson(save);
    }

    public String delete() throws Exception {
        String id = super.req.getParameter("id");
        boolean remove = systemUserService.remove(Integer.parseInt(id));
        return BaseConstants.BASE_REDIRECT + ":" + "SystemUserServlet/list";
    }

    public String batchDel() throws Exception {
        String json = req.getReader().readLine();
        List<Integer> list = JSON.parseArray(json, Integer.class);
        return outJson(systemUserService.batchRemove(list));
    }
}
